package cn.meibang.common.beauty.provider.service;

import cn.apestar.core.base.DelFlagEnum;
import cn.apestar.core.base.YesNoEnum;
import cn.apestar.core.framework.exception.BusinessException;
import cn.apestar.core.utils.DateUtils;
import cn.apestar.core.utils.UuidUtils;
import cn.apestar.user.api.UserAPIService;
import cn.apestar.util.BeanUtilEx;
import cn.meibang.common.beauty.api.IBeautyConsultationOrderAPIService;
import cn.meibang.common.beauty.api.IMeibangUserAPIService;
import cn.meibang.common.beauty.provider.dao.*;
import cn.meibang.common.beauty.provider.domain.*;
import cn.meibang.common.beauty.provider.enums.BcoTypeEnums;
import cn.meibang.common.beauty.provider.enums.ProductTypeEnums;
import cn.meibang.common.beauty.provider.request.ListOrderUserRequest;
import cn.meibang.common.beauty.provider.request.SubmitOrderRequest;
import cn.meibang.common.beauty.provider.response.*;
import cn.meibang.common.beauty.provider.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Created by admin on 2017-5-29.
 */
@Service
public class BeautyConsultationOrderServiceProvider implements IBeautyConsultationOrderAPIService {

    @Autowired
    private BeautyConsultationOrderMapper bcoMapper;

    @Autowired
    private BeautyConsultationOrderQuestionMapper bcoQuestionMapper;

    @Autowired
    private BeautyConsultationOrderAnswerMapper bcoAnswerMapper;

    @Autowired
    private BeautyConsultationOrderRecommendMapper bcoRecommendMapper;

    @Autowired
    private BeautyConsultationOrderRecommendDetailMapper bcoRecommendDetailMapper;

    @Autowired
    private BeautyConsultationOrderUserAnswerMapper bcoUserAnswerMapper;

    @Autowired
    private BeautyConsultationOrderUserProductMapper bcoUserProductMapper;

    @Autowired
    private BeautyConsultationOrderAnswerExtraMapper bcoAnswerExtraMapper;

    @Autowired
    private BeautyConsultationOrderUserAnswerExtraMapper bcoUserAnswerExtraMapper;

    @Autowired
    private BeautyConsultationOrderUserMapper bcoUserMapper;

    @Autowired
    private UserAPIService userAPIService;

    @Autowired
    private IMeibangUserAPIService meibangUserAPIService;

    @Autowired
    private BeautyConsultationOrderUserLatestMapper bcoUserLatestMapper;

    @Autowired
    private BeautyConsultationOrderUserConsultantLatestMapper bcoUserConsultantLatestMapper;

    @Override
    public List<BcoResponse> getAllValidOrder() {
        List<BeautyConsultationOrder> bcos = bcoMapper.selectValidOrder();
        if (bcos.size() == 0) {
            return Collections.emptyList();
        }
        List<BcoResponse> bcoResponses = new ArrayList<>();
        for (BeautyConsultationOrder bco : bcos) {
            BcoResponse bcoRes = this.getOrderById(bco.getId());
            bcoResponses.add(bcoRes);
        }
        return bcoResponses;
    }

    @Override
    public BcoResponse getOrderById(Long id) {
        BeautyConsultationOrder bcoOrder = bcoMapper.selectByPrimaryKey(id);
        if (bcoOrder == null) {
            throw new BusinessException("bco.order.not.found");
        }
        List<BeautyConsultationOrderQuestion> questions = bcoQuestionMapper.selectByOrderId(id);
        List<BeautyConsultationOrderAnswer> answers = bcoAnswerMapper.selectByOrderId(id);
        List<BeautyConsultationOrderRecommend> recommends = bcoRecommendMapper.selectByOrderId(id);
        List<BeautyConsultationOrderRecommendDetail> recommendDetails = bcoRecommendDetailMapper.selectByOrderId(id);
        List<BeautyConsultationOrderAnswerExtra> answerExtras = bcoAnswerExtraMapper.selectByOrderId(id);
        Map<Long, BeautyConsultationOrderAnswerExtra> questionId2AnswerExtra = convert(answerExtras);
        BcoResponse bcoRes = new BcoResponse();
        try {
            BeanUtilEx.copyProperties(bcoRes, bcoOrder);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        // set question start
        List<BcoQuestionResponse> questionResponses = new ArrayList<>();
        for (BeautyConsultationOrderQuestion question : questions) {
            BcoQuestionResponse questionRes = new BcoQuestionResponse();
            try {
                BeanUtilEx.copyProperties(questionRes, question);
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            BeautyConsultationOrderAnswerExtra answerExtra = questionId2AnswerExtra.get(question.getId());
            if (answerExtra != null) {
                OrderUserAnswerExtraVo answerExtraVo = new OrderUserAnswerExtraVo();
                answerExtraVo.setId(answerExtra.getId());
                answerExtraVo.setAnswerTitle(answerExtra.getAnswerTitle());
                questionRes.setUserAnswerExtraVo(answerExtraVo);
            }
            // set answer start
            setAnswers(answers, recommends, recommendDetails, question, questionRes);
            // set answer end
            questionResponses.add(questionRes);
        }
        // set question end
        bcoRes.setQuestions(questionResponses);
        translate(bcoRes, recommendDetails);
        return bcoRes;
    }

    public void translate(BcoResponse bco, List<BeautyConsultationOrderRecommendDetail> list) {
        for (int i = 0; i < list.size(); i++) {
            BeautyConsultationOrderRecommendDetail s = list.get(i);
            ProductTypeEnums l = ProductTypeEnums.get(s.getRecommendType());
            if (s.getProductId() == null)
                continue;
            String productId = s.getProductId().toString();
            switch (l) {
                case A:
                    if (!bco.getCards().contains(productId)) {
                        bco.getCards().add(productId);
                    }
                    break;
                case B:
                    if (!bco.getPackages().contains(productId)) {
                        bco.getPackages().add(productId);
                    }
                    break;
                case C:
                    if (!bco.getProduct().contains(productId)) {
                        bco.getProduct().add(productId);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    @Transactional
    public BeautyConsultationOrderUser submitOrder(SubmitOrderRequest request, String ticket) {
        if (request.getOrderId() == null) {
            throw new BusinessException("order.not.found");
        }
        if (request.getStoreId() == null) {
            throw new BusinessException("store.id.not.found");
        }
        if (request.getUserId() == null && StringUtils.isEmpty(request.getOpenid())) {
            throw new BusinessException("user.not.found");
        }
        if (request.getConsultantId() == null) {
            throw new BusinessException("consultant.id.not.found");
        }
        BeautyConsultationOrder order = bcoMapper.selectByPrimaryKey(request.getOrderId());
        if (order == null) {
            throw new BusinessException("order.not.found");
        }
        if (request.getOrderUserAnswerVos() == null || request.getOrderUserAnswerVos().size() == 0) {
            throw new BusinessException("answer.not.found");
        }
        String uuid = UuidUtils.getUUID();
        // 记录咨询单回答内容
        Date now = DateUtils.now();
        // 记录用户回答的咨询单
        BeautyConsultationOrderUser beautyConsultationOrderUser = createBcoUserRecord(request, uuid, now, order.getType(), ticket);
        // 记录用户最近的咨询顾问
        createBcoUserConsultantLatestRecord(request, uuid);
        List<BeautyConsultationOrderUserAnswer> userAnswers = new ArrayList<>();
        List<BeautyConsultationOrderUserAnswerExtra> userAnswerExtras = new ArrayList<>();
        for (OrderUserAnswerVo vo : request.getOrderUserAnswerVos()) {
            for (Long answerId : vo.getAnswerIds()) {
                BeautyConsultationOrderUserAnswer userAnswer = new BeautyConsultationOrderUserAnswer();
                userAnswer.setTag(uuid);
                userAnswer.setOrderId(request.getOrderId());
                userAnswer.setUserId(request.getUserId());
                userAnswer.setOpenid(request.getOpenid());
                userAnswer.setQuestionId(vo.getQuestionId());
                userAnswer.setAnswerId(answerId);
                userAnswer.setDelFlag(DelFlagEnum.DEL_FALSE.getValue());
                userAnswer.setCreateBy(request.getUserId());
                userAnswer.setCreateDate(now);
                userAnswer.setUpdateBy(request.getUserId());
                userAnswer.setUpdateDate(now);
                userAnswers.add(userAnswer);
            }
            OrderUserAnswerExtraVo userAnswerExtraVo = vo.getUserAnswerExtraVo();
            if (userAnswerExtraVo != null && StringUtils.isNotEmpty(userAnswerExtraVo.getAnswerContent())) {
                BeautyConsultationOrderUserAnswerExtra userAnswerExtra = new BeautyConsultationOrderUserAnswerExtra();
                userAnswerExtra.setExtraAnswerId(userAnswerExtraVo.getId());
                userAnswerExtra.setExtraAnswerContent(userAnswerExtraVo.getAnswerContent());
                userAnswerExtra.setTag(uuid);
                userAnswerExtra.setOrderId(request.getOrderId());
                userAnswerExtra.setUserId(request.getUserId());
                userAnswerExtra.setOpenid(request.getOpenid());
                userAnswerExtra.setQuestionId(vo.getQuestionId());
                userAnswerExtra.setDelFlag(DelFlagEnum.DEL_FALSE.getValue());
                userAnswerExtra.setCreateBy(request.getUserId());
                userAnswerExtra.setCreateDate(now);
                userAnswerExtra.setUpdateBy(request.getUserId());
                userAnswerExtra.setUpdateDate(now);
                userAnswerExtras.add(userAnswerExtra);
            }
        }
        for (BeautyConsultationOrderUserAnswer userAnswer : userAnswers) {
            bcoUserAnswerMapper.insert(userAnswer);
        }
        for (BeautyConsultationOrderUserAnswerExtra userAnswerExtra : userAnswerExtras) {
            bcoUserAnswerExtraMapper.insert(userAnswerExtra);
        }
        // 记录用户勾选的产品
        if (request.getOrderUserProductVos() != null && request.getOrderUserAnswerVos().size() > 0) {
            List<BeautyConsultationOrderUserProduct> userProducts = new ArrayList<>();
            for (OrderUserProductVo vo : request.getOrderUserProductVos()) {
                BeautyConsultationOrderUserProduct userProduct = new BeautyConsultationOrderUserProduct();
                userProduct.setTag(uuid);
                userProduct.setOrderId(request.getOrderId());
                userProduct.setUserId(request.getUserId());
                userProduct.setOpenid(request.getOpenid());
                userProduct.setProductId(vo.getProductId());
                userProduct.setProductName(vo.getProductName());
                userProduct.setRecommendType(vo.getRecommendType());
                userProduct.setPrice(vo.getPrice());
                userProduct.setConsultantId(request.getConsultantId());
                userProduct.setConsultantName(request.getConsultantName());
                userProduct.setDelFlag(DelFlagEnum.DEL_FALSE.getValue());
                userProduct.setCreateBy(request.getUserId());
                userProduct.setCreateDate(now);
                userProduct.setUpdateBy(request.getUserId());
                userProduct.setUpdateDate(now);
                userProducts.add(userProduct);
            }
            for (BeautyConsultationOrderUserProduct userProduct : userProducts) {
                bcoUserProductMapper.insert(userProduct);
            }
        }
        return beautyConsultationOrderUser;
    }

    /**
     * 记录用户最近的咨询顾问
     *
     * @param request
     * @param uuid
     */
    private void createBcoUserConsultantLatestRecord(SubmitOrderRequest request, String uuid) {
        if (request.getUserId() != null && request.getUserId() > 0) {
            bcoUserConsultantLatestMapper.delete(request.getUserId(), request.getStoreId(), request.getConsultantId());
        }
        if (StringUtils.isNotEmpty(request.getOpenid())) {
            bcoUserConsultantLatestMapper.deleteByOpenid(request.getOpenid(), request.getStoreId(), request.getConsultantId());
        }
        BeautyConsultationOrderUserConsultantLatest bcoUserConsultantLatest = new BeautyConsultationOrderUserConsultantLatest();
        bcoUserConsultantLatest.setConsultantId(request.getConsultantId());
        bcoUserConsultantLatest.setStoreId(request.getStoreId());
        bcoUserConsultantLatest.setStoreName(request.getStoreName());
        bcoUserConsultantLatest.setConsultantName(request.getConsultantName());
        bcoUserConsultantLatest.setConsultantImg(request.getConsultantImg());
        bcoUserConsultantLatest.setTag(uuid);
        bcoUserConsultantLatest.setUserId(request.getUserId());
        bcoUserConsultantLatest.setOpenid(request.getOpenid());
        bcoUserConsultantLatestMapper.insert(bcoUserConsultantLatest);
    }

    private BeautyConsultationOrderUser createBcoUserRecord(SubmitOrderRequest request, String uuid, Date now, String orderType, String ticket) {
        String userName = "客户";
        if (request.getUserId() != null && request.getUserId() > 0) {
            List<MeibangUserInfoVo> meibangUserInfoVos = meibangUserAPIService.listMeibangUserInfo(Arrays.asList(request.getUserId()), ticket);
            if (meibangUserInfoVos.size() > 0) {
                userName = meibangUserInfoVos.get(0).getUserName();
            } else {
                userName = "客户";
            }
        }
        if (StringUtils.isNotEmpty(request.getOpenid()) && "客户".equals(userName)) {
            MeibangUserInfoVo meibangUserInfoByOpenid = meibangUserAPIService.getMeibangUserInfoByOpenid(request.getOpenid(), ticket);
            if (meibangUserInfoByOpenid != null) {
                userName = meibangUserInfoByOpenid.getUserName();
            }
        }
        // 增加用户咨询记录
        BeautyConsultationOrderUser bcoUser = new BeautyConsultationOrderUser();
        bcoUser.setConsultantId(request.getConsultantId());
        bcoUser.setUserId(request.getUserId());
        bcoUser.setOpenid(request.getOpenid());
        bcoUser.setCreateBy(request.getUserId());
        bcoUser.setCreateDate(now);
        bcoUser.setOrderId(request.getOrderId());
        bcoUser.setTitle(userName + "的咨询单");
        bcoUser.setTag(uuid);
        bcoUser.setOrderType(orderType);
        bcoUser.setStoreId(request.getStoreId());
        bcoUser.setIsDeal(YesNoEnum.No.getValue());
        bcoUserMapper.insert(bcoUser);
        // 更新用户最新的咨询记录
        if (request.getUserId() != null) {
            bcoUserLatestMapper.delete(request.getUserId(), orderType);
        }
        if (StringUtils.isNotEmpty(request.getOpenid())) {
            bcoUserLatestMapper.deleteByOpenidAndOrderType(request.getOpenid(), orderType);
        }

        BeautyConsultationOrderUserLatest bcoUserLatest = new BeautyConsultationOrderUserLatest();
        bcoUserLatest.setConsultantId(request.getConsultantId());
        bcoUserLatest.setUserId(request.getUserId());
        bcoUserLatest.setOpenid(request.getOpenid());
        bcoUserLatest.setCreateBy(request.getUserId());
        bcoUserLatest.setCreateDate(now);
        bcoUserLatest.setOrderId(request.getOrderId());
        bcoUserLatest.setTitle(userName + "的咨询单");
        bcoUserLatest.setTag(uuid);
        bcoUserLatest.setOrderType(orderType);
        bcoUserLatest.setStoreId(request.getStoreId());
        bcoUserLatestMapper.insert(bcoUserLatest);
        return bcoUser;
    }

    @Override
    public SubmitOrderResponse getLatestSubmitOrder(Long orderId, Long userId, String openid) {
        if ((userId == null || userId == 0) && StringUtils.isEmpty(openid)) {
            throw new BusinessException("user.not.found");
        }
        SubmitOrderResponse response = new SubmitOrderResponse();
        response.setOrderId(orderId);
        response.setUserId(userId);
        response.setOpenid(openid);
        BeautyConsultationOrderUserAnswer userAnswer = bcoUserAnswerMapper.selectLatest(orderId, userId, openid);
        if (userAnswer == null) {
            return response;
        }
        List<BeautyConsultationOrderUserAnswer> userAnswers = bcoUserAnswerMapper.selectByTag(userAnswer.getTag());
        List<BeautyConsultationOrderUserAnswerExtra> userAnswerExtras = bcoUserAnswerExtraMapper.selectByTag(userAnswer.getTag());
        List<OrderUserAnswerVo> userAnswerVos = convert2UserAnswerVo(userAnswers, userAnswerExtras);
        response.setOrderUserAnswerVos(userAnswerVos);

        List<BeautyConsultationOrderUserProduct> userProducts = bcoUserProductMapper.selectByTag(userAnswer.getTag());
        List<OrderUserProductVo> userProductVos = convert2UserProductVo(userProducts);
        response.setOrderUserProductVos(userProductVos);
        return response;
    }

    @Override
    public List<UserOrderResponse> getUserOrderResponse(Long userId, String openid) {
        if ((userId == null || userId == 0) && StringUtils.isEmpty(openid)) {
            throw new BusinessException("user.not.found");
        }
        List<UserOrderResponse> result = new ArrayList<>();
        List<BeautyConsultationOrderUserLatest> orderUsers = bcoUserLatestMapper.select(userId, openid);
        for (BeautyConsultationOrderUserLatest orderUserLatest : orderUsers) {
            Long orderId = orderUserLatest.getOrderId();
            BcoResponse bcoResponse = this.getOrderById(orderId);
            if (bcoResponse == null) {
                continue;
            }
            UserOrderResponse userOrderResponse = new UserOrderResponse();
            userOrderResponse.setOrderId(orderId);
            userOrderResponse.setType(bcoResponse.getType());
            BcoTypeEnums bcoTypeEnums = BcoTypeEnums.get(bcoResponse.getType());
            userOrderResponse.setTypeName(bcoTypeEnums == null ? "" : bcoTypeEnums.getCode());
            userOrderResponse.setConsultantId(orderUserLatest.getConsultantId());
            userOrderResponse.setUserId(orderUserLatest.getCreateBy());
            userOrderResponse.setOrderTitle(orderUserLatest.getTitle());
            List<UserQuestionResponse> userQuestionResponses = new ArrayList<>();
            if (bcoResponse.getQuestions() == null || bcoResponse.getQuestions().size() == 0) {
                continue;
            }
            for (BcoQuestionResponse bcoQuestionResponse : bcoResponse.getQuestions()) {
                UserQuestionResponse userQuestionResponse = new UserQuestionResponse();
                userQuestionResponse.setQuestionTitle(bcoQuestionResponse.getQuestionTitle());
                userQuestionResponse.setQuestionId(bcoQuestionResponse.getId());
                userQuestionResponses.add(userQuestionResponse);
            }
            // 设置问题的答案
            setQuestionAnswerWhenGetUserOrder(orderUserLatest, bcoResponse, userQuestionResponses);
            // 设置问题的额外答案
            setUserAnswerExtraWhenGetUserOrder(orderUserLatest, bcoResponse, userQuestionResponses);
            userOrderResponse.setUserQuestionResponses(userQuestionResponses);
            result.add(userOrderResponse);
        }
        return result;
    }

    @Override
    public List<BcoUserResponse> listOrderUser(ListOrderUserRequest request, Long currentUserId, String ticket) {
        if (request.getEndDate() != null) {
            request.setEndDate(DateUtils.addDay(request.getEndDate(), 1));
        }
        request.setConsultantId(currentUserId);
        // 获取技师的订单
        List<BeautyConsultationOrderUserLatest> beautyConsultationOrderUserLatests = bcoUserLatestMapper.selectByListRequest(request);
        List<Long> meibangUserIds = new ArrayList<>();
        for (BeautyConsultationOrderUserLatest orderUser : beautyConsultationOrderUserLatests) {
            meibangUserIds.add(orderUser.getCreateBy());
        }
        List<MeibangUserInfoVo> meibangUserInfoVos = meibangUserAPIService.listMeibangUserInfo(meibangUserIds, ticket);
        Map<Long, MeibangUserInfoVo> userId2UserInfoMap = new HashMap<>();
        for (MeibangUserInfoVo userInfo : meibangUserInfoVos) {
            userId2UserInfoMap.put(userInfo.getMemberId(), userInfo);
        }
        List<BcoUserResponse> bcoUserResponses = copyProperties(beautyConsultationOrderUserLatests);
        for (BcoUserResponse res : bcoUserResponses) {
            MeibangUserInfoVo meibangUserInfoVo = userId2UserInfoMap.get(res.getCreateBy());
            if (meibangUserInfoVo != null) {
                res.setAmount(meibangUserInfoVo.getAmount());
                res.setHeadImg(meibangUserInfoVo.getHeadImg());
                res.setPhone(meibangUserInfoVo.getPhone());
                res.setRealName(meibangUserInfoVo.getRealName());
                res.setUserName(meibangUserInfoVo.getUserName());
            }
        }
        return bcoUserResponses;
    }

    @Override
    public void feedbackDeal(Long id) {
        BeautyConsultationOrderUser beautyConsultationOrderUser = bcoUserMapper.selectByPrimaryKey(id);
        beautyConsultationOrderUser.setIsDeal(YesNoEnum.Yes.getValue());
        beautyConsultationOrderUser.setDealDate(DateUtils.now());
        bcoUserMapper.updateByPrimaryKey(beautyConsultationOrderUser);
    }

    private List<BcoUserResponse> copyProperties(List<BeautyConsultationOrderUserLatest> beautyConsultationOrderUserLatests) {
        List<BcoUserResponse> result = new ArrayList<>();
        for (BeautyConsultationOrderUserLatest orderUser : beautyConsultationOrderUserLatests) {
            BcoUserResponse res = new BcoUserResponse();
            try {
                BeanUtilEx.copyProperties(res, orderUser);
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            result.add(res);
        }
        return result;
    }

    private void setUserAnswerExtraWhenGetUserOrder(BeautyConsultationOrderUserLatest orderUser, BcoResponse bcoResponse,
                                                    List<UserQuestionResponse> userQuestionResponses) {
        List<BeautyConsultationOrderUserAnswerExtra> userAnswerExtras = bcoUserAnswerExtraMapper.selectByTag(orderUser.getTag());
        Map<Long, BeautyConsultationOrderUserAnswerExtra> questionId2AnswerExtraMap = new HashMap<>();
        for (BeautyConsultationOrderUserAnswerExtra answerExtra : userAnswerExtras) {
            questionId2AnswerExtraMap.put(answerExtra.getQuestionId(), answerExtra);
        }
        Map<Long, OrderUserAnswerExtraVo> question2BcoAnswerExtraResponseMap = getQuestion2BcoAnswerExtraResponseMap(bcoResponse);
        for (UserQuestionResponse userQuestionResponse : userQuestionResponses) {
            OrderUserAnswerExtraVo answerExtraVo = question2BcoAnswerExtraResponseMap.get(userQuestionResponse.getQuestionId());
            BeautyConsultationOrderUserAnswerExtra userAnswerExtra = questionId2AnswerExtraMap.get(userQuestionResponse.getQuestionId());
            if (answerExtraVo != null && userAnswerExtra != null) {
                answerExtraVo.setAnswerContent(userAnswerExtra.getExtraAnswerContent());
                userQuestionResponse.setUserAnswerExtraVo(answerExtraVo);
                List<LatestOrderUserAnswerVo> answers = userQuestionResponse.getAnswers();
                if (answers == null) {
                    answers = new ArrayList<>();
                    userQuestionResponse.setAnswers(answers);
                }
                LatestOrderUserAnswerVo latestOrderUserAnswerVo = new LatestOrderUserAnswerVo();
                latestOrderUserAnswerVo.setAnswerTitle(userAnswerExtra.getExtraAnswerContent());
                answers.add(latestOrderUserAnswerVo);
            }
        }
    }

    private void setQuestionAnswerWhenGetUserOrder(BeautyConsultationOrderUserLatest orderUser, BcoResponse bcoResponse,
                                                   List<UserQuestionResponse> userQuestionResponses) {
        Map<Long, BcoAnswerResponse> answerId2AnswerResponse = getAnswerId2BcoAnswerResponseMap(bcoResponse);
        List<BeautyConsultationOrderUserAnswer> userAnswers = bcoUserAnswerMapper.selectByTag(orderUser.getTag());
        for (UserQuestionResponse userQuestionResponse : userQuestionResponses) {
            for (BeautyConsultationOrderUserAnswer userAnswer : userAnswers) {
                if (!userQuestionResponse.getQuestionId().equals(userAnswer.getQuestionId())) {
                    continue;
                }
                List<LatestOrderUserAnswerVo> answers = userQuestionResponse.getAnswers();
                if (answers == null) {
                    answers = new ArrayList<>();
                    userQuestionResponse.setAnswers(answers);
                }
                BcoAnswerResponse bcoAnswerResponse = answerId2AnswerResponse.get(userAnswer.getAnswerId());
                if (bcoAnswerResponse != null) {
                    if (bcoAnswerResponse.getAnswerPriceStart() != null && bcoAnswerResponse.getAnswerPriceEnd() != null
                            && (bcoAnswerResponse.getAnswerPriceStart() > 0 || bcoAnswerResponse.getAnswerPriceEnd() > 0)) {
                        LatestOrderUserAnswerVo latestOrderUserAnswerVo = new LatestOrderUserAnswerVo();
                        latestOrderUserAnswerVo.setAnswerTitle(bcoAnswerResponse.getAnswerPriceStart() + "-" + bcoAnswerResponse.getAnswerPriceEnd());
                        answers.add(latestOrderUserAnswerVo);
                    } else {
                        LatestOrderUserAnswerVo latestOrderUserAnswerVo = new LatestOrderUserAnswerVo();
                        latestOrderUserAnswerVo.setAnswerTitle(bcoAnswerResponse.getAnswerTitle());
                        latestOrderUserAnswerVo.setAnswerImg(bcoAnswerResponse.getAnswerImageUrl());
                        answers.add(latestOrderUserAnswerVo);
                    }
                }
            }
        }
    }

    private Map<Long, BcoAnswerResponse> getAnswerId2BcoAnswerResponseMap(BcoResponse bcoResponse) {
        Map<Long, BcoAnswerResponse> answerId2AnswerResponse = new HashMap<>();
        List<BcoQuestionResponse> questions = bcoResponse.getQuestions();
        for (BcoQuestionResponse bcoQuestionResponse : questions) {
            for (BcoAnswerResponse bcoAnswerResponse : bcoQuestionResponse.getAnswers()) {
                answerId2AnswerResponse.put(bcoAnswerResponse.getId(), bcoAnswerResponse);
            }
        }
        return answerId2AnswerResponse;
    }

    private Map<Long, OrderUserAnswerExtraVo> getQuestion2BcoAnswerExtraResponseMap(BcoResponse bcoResponse) {
        Map<Long, OrderUserAnswerExtraVo> questionId2AnswerExtraResponse = new HashMap<>();
        List<BcoQuestionResponse> questions = bcoResponse.getQuestions();
        for (BcoQuestionResponse bcoQuestionResponse : questions) {
            if (bcoQuestionResponse.getUserAnswerExtraVo() != null) {
                questionId2AnswerExtraResponse.put(bcoQuestionResponse.getId(), bcoQuestionResponse.getUserAnswerExtraVo());
            }
        }
        return questionId2AnswerExtraResponse;
    }

    private Map<Long, BeautyConsultationOrderAnswerExtra> convert(List<BeautyConsultationOrderAnswerExtra> answerExtras) {
        Map<Long, BeautyConsultationOrderAnswerExtra> result = new HashMap<>();
        for (BeautyConsultationOrderAnswerExtra obj : answerExtras) {
            result.put(obj.getQuestionId(), obj);
        }
        return result;
    }

    private List<OrderUserProductVo> convert2UserProductVo(List<BeautyConsultationOrderUserProduct> userProducts) {
        List<OrderUserProductVo> result = new ArrayList<>();
        for (BeautyConsultationOrderUserProduct userProduct : userProducts) {
            OrderUserProductVo vo = new OrderUserProductVo();
            vo.setProductId(userProduct.getProductId());
            vo.setProductName(userProduct.getProductName());
            vo.setRecommendType(userProduct.getRecommendType());
            result.add(vo);
        }
        return result;
    }

    private List<OrderUserAnswerVo> convert2UserAnswerVo(List<BeautyConsultationOrderUserAnswer> userAnswers,
                                                         List<BeautyConsultationOrderUserAnswerExtra> userAnswerExtras) {
        Map<Long, List<Long>> question2AnswerListMap = new HashMap<>();
        for (BeautyConsultationOrderUserAnswer userAnswer : userAnswers) {
            List<Long> answerIds = question2AnswerListMap.get(userAnswer.getQuestionId());
            if (answerIds == null) {
                answerIds = new ArrayList<>();
                question2AnswerListMap.put(userAnswer.getQuestionId(), answerIds);
            }
            answerIds.add(userAnswer.getAnswerId());
        }
        Map<Long, BeautyConsultationOrderUserAnswerExtra> question2UserAnswerExtraMap = new HashMap<>();
        for (BeautyConsultationOrderUserAnswerExtra vo : userAnswerExtras) {
            question2UserAnswerExtraMap.put(vo.getQuestionId(), vo);
        }
        List<OrderUserAnswerVo> result = new ArrayList<>();
        for (Map.Entry<Long, List<Long>> entry : question2AnswerListMap.entrySet()) {
            OrderUserAnswerVo vo = new OrderUserAnswerVo();
            vo.setQuestionId(entry.getKey());
            vo.setAnswerIds(entry.getValue());
            BeautyConsultationOrderUserAnswerExtra userAnswerExtra = question2UserAnswerExtraMap.get(entry.getKey());
            if (userAnswerExtra != null) {
                OrderUserAnswerExtraVo userAnswerExtraVo = new OrderUserAnswerExtraVo();
                userAnswerExtraVo.setId(userAnswerExtra.getId());
                userAnswerExtraVo.setAnswerContent(userAnswerExtra.getExtraAnswerContent());
                vo.setUserAnswerExtraVo(userAnswerExtraVo);
            }
            result.add(vo);
        }
        return result;
    }

    private void setAnswers(List<BeautyConsultationOrderAnswer> answers, List<BeautyConsultationOrderRecommend> recommends,
                            List<BeautyConsultationOrderRecommendDetail> recommendDetails, BeautyConsultationOrderQuestion question, BcoQuestionResponse questionRes) {
        List<BcoAnswerResponse> answerResponses = new ArrayList<>();
        for (BeautyConsultationOrderAnswer answer : answers) {
            if (!answer.getQuestionId().equals(question.getId())) {
                continue;
            }
            BcoAnswerResponse answerRes = new BcoAnswerResponse();
            try {
                BeanUtilEx.copyProperties(answerRes, answer);
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            // set recommend start
            setRecommend(recommends, recommendDetails, answer, answerRes);
            // set recommend end
            answerResponses.add(answerRes);
        }
        questionRes.setAnswers(answerResponses);
    }

    private void setRecommend(List<BeautyConsultationOrderRecommend> recommends, List<BeautyConsultationOrderRecommendDetail> recommendDetails,
                              BeautyConsultationOrderAnswer answer, BcoAnswerResponse answerRes) {
        List<BcoRecommendResponse> recommendResponses = new ArrayList<>();
        for (BeautyConsultationOrderRecommend recommend : recommends) {
            if (!recommend.getAnswerId().equals(answer.getId())) {
                continue;
            }
            BcoRecommendResponse recommendRes = new BcoRecommendResponse();
            try {
                BeanUtilEx.copyProperties(recommendRes, recommend);
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            // set recommend detail start
            setRecommendDetails(recommendDetails, recommend, recommendRes);
            // set recommend detail end
            recommendResponses.add(recommendRes);
        }
        if (recommendResponses.size() > 0) {
            answerRes.setRecommend(recommendResponses.get(0));
        }
    }

    private void setRecommendDetails(List<BeautyConsultationOrderRecommendDetail> recommendDetails, BeautyConsultationOrderRecommend recommend,
                                     BcoRecommendResponse recommendRes) {
        List<BeautyConsultationOrderRecommendDetail> recommendDetailResponses = new ArrayList<>();
        for (BeautyConsultationOrderRecommendDetail detail : recommendDetails) {
            if (!detail.getRecommendId().equals(recommend.getId())) {
                continue;
            }
            recommendDetailResponses.add(detail);
        }
        recommendRes.setDetails(recommendDetailResponses);
    }
}
